const Base = require('./base.js');


module.exports = class extends Base {

	constructor(ctx) {
		super(ctx);
		this.unit = this.model("system/unit");
	}

	async indexAction() {
		let pid = this.get("pid");
		let units = await this.unit.getChilds(pid);
		if(this.isPost) {
			return this.success(units);
		}
		this.assign("units", units);
		
		return this.display();
	}

	async childAction() {

		let pid = this.post("pid");
		let childs = await this.unit.getChilds(pid);
		this.assign("units", childs);
		return this.display();

	}

	async treeAction() {

		let pid = this.get("pid");

		let units = await this.unit.getChilds(pid);
		let data = [];

		if(!think.isEmpty(units)) {

			units.forEach(function(o) {
				let unit = {};
				unit.id = o.id;
				unit.text = o.name;
				unit.children = o.hasChildren == 1 ? true : false;
				data.push(unit);
			});

		}

		return this.json(data);

	}

	async addAction() {

		if(this.isGet) {
			let pid = this.get("pid");

			if(pid) {
				let unit = await this.unit.findOne(pid);
				this.assign("parentUnit", unit);
			}
			return this.display();

		}

		let posts = this.post();
		let user = await this.session("user");

		let unit_id = await this.unit.add({

			name: posts.name,
			code: posts.code,
			pid: posts.parentId,
			description: posts.description,
			address: posts.address,
			mobile: posts.mobile,
			tel: posts.tel,
			sort: posts.sort,
			create_time: new Date().valueOf(),
			created_by: user.id

		});

		if(unit_id == 0) {
			return this.fail("添加失败");
		}

		await this.unit.setOne(posts.parentId, {
			hasChildren: 1
		});

		return this.success("添加成功");
	}
	async editAction() {

		if(this.isGet) {
			let id = this.get("id");

			if(id) {
				let unit = await this.unit.findOne(id);

				if(unit.pid) {
					let parentUnit = await this.unit.findOne(unit.pid);

					this.assign("parentUnit", parentUnit);

				}

				this.assign("unit", unit);
				return this.display();
			}

		}

		let posts = this.post();

		let rows = await this.unit.setOne(posts.id, {
			name: posts.name,
			code: posts.code,
			pid: posts.parentId,
			description: posts.description,
			address: posts.address,
			mobile: posts.mobile,
			tel: posts.tel,
			sort: posts.sort,
			update_time: new Date().valueOf()
		});

		if(rows == 0) {
			return this.fail("修改失败");
		}

		await this.unit.setOne(posts.parentId, {
			hasChildren: 1
		});
		return this.success("修改成功");

	}
	async detailAction() {
		let id = this.get("id");
		let unit = await this.unit.findOne(id);
		this.assign("unit", unit);
		unit.create_time = think.datetime(unit.create_time);

		return this.display();
	}

	async deleteAction() {

		let id = this.post("id");
		let rows = await this.unit.where({
			id: id
		}).delete();
		if(rows == 0) {
			return this.fail("删除失败");
		}
		return this.success("删除成功");

	}
};